<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !revokeInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        @returnBack="returnBack"
        title="移库单明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
      >
        <template v-slot:full-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canChcek" @click="check()">审核</el-button>
          <el-button v-if="canReject" @click="reject()">驳回</el-button>
          <el-button v-if="canTransfer" @click="transfer">移库</el-button>
          <el-button v-if="canCancel" @click="doCancel">取消</el-button>
          <el-button v-if="canCancelPutTransfer" @click="cancelPutTransfer"
            >取消上架</el-button
          >
          <el-button v-if="canCancelDownTransfer" @click="cancelDownTransfer"
            >取消拣货</el-button
          >
          <el-button v-if="canRevoke" @click="revoke">撤回</el-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <!--<el-button v-if="canConsume" @click="tally">移库并消耗</el-button>-->
          <el-button v-if="canRevokable" @click="revokable">逆向移库</el-button>
          <!-- <el-button v-if="canTransferPutShelf" @click="transferPutShelf"
            >移库并上架</el-button
          > -->
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button v-if="canPrint" @click="print">打印</el-button> -->
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="infoList"
              :label-width="infoList.labelWidth"
            />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" :sums="tableInfo.sums" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @callbackSum="callbackSum"
              >
                <template v-slot:col-storeBatchNumber="scope">
                  <span
                    v-if="scope.row.isConsignBusiness === 1"
                    class="consignBusiness-text"
                    >寄</span
                  >
                  <span
                    v-if="scope.row.isEstimationStockBusiness === 1"
                    class="estimationStockBusiness-text"
                    >暂</span
                  >
                  <span>{{ scope.row.storeBatchNumber }}</span>
                </template>
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <transfer-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.orderId"
      @returnModify="returnModify"
    />
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.info"
    />
    <Revoke
      v-if="revokeInfo.visible"
      :id="revokeInfo.id"
      v-model:visible="revokeInfo.visible"
      :title="revokeInfo.title"
    />
    <PageDialog
      v-show="dialogUserInfo.visible"
      :title="dialogUserInfo.title"
      v-model:visible="dialogUserInfo.visible"
      :width="dialogUserInfo.width"
      :bt-loading="dialogUserInfo.btLoading"
      :bt-list="dialogUserInfo.btList"
      @reset="handleClose"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formUserInfo.ref"
        :data="formUserInfo.data"
        :field-list="formUserInfo.fieldList"
        :label-width="formUserInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
      </page-form>
    </PageDialog>
  </div>
</template>

<script setup name="transferOrderDetail">
import {
  transferAndPutShelf,
  transferOrderDetailsCustomizeListAll,
  detailTransferOrder,
  exportExcelTransferOrder,
  submitTransferOrder,
  checkTransferOrder,
  rejectTransferOrder,
  transferTransferOrder,
  tallyTransferOrder,
  revokeTransferOrder,
  getTransferOrderPrint,
  validateRevoke,
  transferCancelPut,
  transfersCancel,
  transfersCancelDownShelf,
} from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderAffairAll } from '../../../api/affair'
import { fatchTemplateByCode } from '@/api/base'
import Revoke from './revoke'
import PageDialog from '@/components/PageDialog/index'
import PageForm from '@/components/PageForm/index'
import { getRrgUserAll } from '@/api/base.js'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const BasicInformation = defineAsyncComponent(() =>
  import('@/components/BasicInformation/index')
)
const PageTable = defineAsyncComponent(() =>
  import('@/components/PageTable/index')
)
const TransferOrderModify = defineAsyncComponent(() => import('./modify'))
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const IndividualDetails = defineAsyncComponent(() =>
  import('./IndividualDetails')
)
const props = defineProps({
  visible: {
    type: Boolean,
    default: function () {
      return false
    },
  },
  tableRow: {
    type: Object,
    default: function () {
      return {}
    },
  },
})

const infoList = reactive({
  data: {},
  fieldList: [
    { label: '移库单号', value: 'orderNo', type: 'text' },
    { label: '出库部门', value: 'exportDeptName', type: 'text' },
    { label: '出库仓库', value: 'exportDepotName', type: 'text' },
    { label: '入库部门', value: 'storeDeptName', type: 'text' },
    { label: '入库仓库', value: 'storeDepotName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '移库人', value: 'transferUserName', type: 'text' },
    { label: '移库时间', value: 'transferTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '最后更新人', value: 'updateUserName', type: 'text' },
    { label: '最后更新时间', value: 'updateTime', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'text' },
  ],
  labelWidth: '110px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.id,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = reactive({
  visible: false,
  title: '',
})

// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { label: '数量', value: 'qty', formatter: proxy.$fn.qtyFormatter },
    {
      label: '金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  sums: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: showDetail,
        show: proxy.$permission('transferOrder:IndividualDetails'),
        ifRender: ifIndividualDetails,
      },
    ],
  },
})
const affairTableInfo = reactive({
  api: orderAffairAll,
  query: {
    orderType: 2,
    orderId: props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = reactive({
  visible: false,
  query: {},
  info: {},
})
const revokeInfo = reactive({
  visible: false,
  title: '移库撤回',
  id: '',
})
const dialogUserInfo = reactive({
  type: '',
  visible: false,
  title: '选择上架人员',
  btLoading: false,
  width: '400px',
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: savePutShelfUser,
      show: true,
    },
  ],
})
const formUserInfo = reactive({
  data: {
    id: '',
    putShelfUser: -2,
  },
  fieldList: [
    {
      label: '姓名',
      value: 'putShelfUser',
      type: 'select',
      filterable: true,
      list: 'userList',
      event: 'userName',
    },
  ],
})
const listTypeInfo = reactive({
  userList: [],
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSubmit = computed(() => {
  return proxy.$permission('transferOrder:submit') && infoList.data.status === 1
})
const canChcek = computed(() => {
  return (
    proxy.$store.state.permission.systemConfig.move_stock_approval === 1 &&
    proxy.$permission('transferOrder:check') &&
    infoList.data.status === 4
  )
})
const canReject = computed(() => {
  return (
    proxy.$store.state.permission.systemConfig.move_stock_approval === 1 &&
    proxy.$permission('transferOrder:reject') &&
    infoList.data.status === 4
  )
})
const canTransfer = computed(() => {
  return (
    proxy.$permission('transferOrder:transfer') && infoList.data.status === 2
  )
})
const canCancel = computed(() => {
  return (
    proxy.$permission('transferOrder:cancel') &&
    infoList.data.status === 2 &&
    infoList.data.exportDepotIsCargoSpaceManage === 1
  )
})
const canCancelPutTransfer = computed(() => {
  return (
    proxy.$permission('transferOrder:cancelPut') && infoList.data.status === 5
  )
})
const canCancelDownTransfer = computed(() => {
  return (
    proxy.$permission('transferOrder:cancelDown') && infoList.data.status === 6
  )
})
const canRevoke = computed(() => {
  if (proxy.$store.state.permission.systemConfig.move_stock_approval === 1) {
    return (
      proxy.$permission('transferOrder:revoke') &&
      infoList.data.status === 4 &&
      infoList.data.orderSourceType !== 75
    )
  }
  return (
    proxy.$permission('transferOrder:revoke') &&
    infoList.data.status === 2 &&
    infoList.data.orderSourceType !== 75 &&
    infoList.data.exportDepotIsCargoSpaceManage === 0
  )
})
const canRevokable = computed(() => {
  return (
    proxy.$permission('transferOrder:revokable') &&
    infoList.data.status === 3 &&
    infoList.data.orderSourceType !== 75
  )
})
const canConsume = computed(() => {
  return (
    proxy.$permission('transferOrder:consume') &&
    infoList.data.status === 2 &&
    !infoList.data.withTable
  )
})
const canUpdate = computed(() => {
  return proxy.$permission('transferOrder:update') && infoList.data.status === 1
})
const canPrint = computed(() => {
  return proxy.$permission('transferOrder:print') && infoList.data.status !== 1
})
const canExcel = computed(() => {
  return (
    proxy.$permission('transferOrder:exportExcel') && infoList.data.status !== 1
  )
})
const canTransferPutShelf = computed(() => {
  return (
    proxy.$permission('transferOrder:transferAndPutShelf') &&
    infoList.data.status === 2 &&
    infoList.data.isCargoSpaceManage === 1
  )
})
let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('transferOrder:price'),
    hidden: true,
  },
  storeBatchNumber: {
    label: '入库批次号',
    value: 'storeBatchNumber',
    align: 'left',
    isConsigAndEst: true, //是否显示寄暂
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('transferOrder:price'),
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getUserList()
function returnModify() {
  getMain()
  getList()
}
function ifIndividualDetails(row) {
  return (
    infoList.data.exportDepotIsCargoSpaceManage === 0 ||
    (infoList.data.exportDepotIsCargoSpaceManage === 1 && row.status === 2) ||
    (infoList.data.exportDepotIsCargoSpaceManage === 1 && row.status === 3) ||
    (infoList.data.exportDepotIsCargoSpaceManage === 1 && row.status === 5) ||
    (infoList.data.exportDepotIsCargoSpaceManage === 1 && row.status === 7)
  )
}
function callbackSum(val) {
  tableInfo.sums = []
  if (val && val.length) {
    tableInfo.sums = val.filter((item) => item)
  }
}
//获取人员列表
function getUserList() {
  let params = {
    sort: 'create_time desc',
  }
  getRrgUserAll(params).then((res) => {
    if (res && res.success) {
      let arr = [{ key: '暂不选择', value: -2, userName: '' }]
      if (res.data && res.data.length) {
        let data = res.data.map((item) => {
          return {
            key: item.name,
            value: item.id,
            userName: item.userName,
          }
        })
        listTypeInfo.userList = arr.concat(data)
      }
    }
  })
}
//上架
function savePutShelfUser() {
  transferAndPutShelf(formUserInfo.data).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
      handleClose()
    }
  })
}
//关闭选择拣货人员弹窗
function handleClose() {
  dialogUserInfo.visible = false
  formUserInfo.data = {
    id: '',
    putShelfUser: -2,
  }
}
function transferPutShelf() {
  dialogUserInfo.visible = true
  formUserInfo.data.id = infoList.data.id
}
function returnBack() {
  emit('returnBack', false)
}
function showDetail(row) {
  individualInfo.visible = true
  individualInfo.info = row
  individualInfo.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: row.groupConcatIds,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.tableRow.id,
    },
  }
}
function getMain() {
  detailTransferOrder(props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
    }
  })
}
function getList() {
  transferOrderDetailsCustomizeListAll(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}

function update() {
  modifyInfo.orderId = infoList.data.id
  modifyInfo.title = '修改移库单'
  modifyInfo.visible = true
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'stockTransferDetail',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: infoList.data.id,
            orderNo: infoList.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.query,
            }),
          },
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.orderNo,
      orderId: props.tableRow.id,
      tempCode: 'stockTransferDetail',
      orderType: 2,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: infoList.data.id,
      orderNo: infoList.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {
      customParam: JSON.stringify({
        ...filterInfo.query,
      }),
    },
  })
  popoverVisible.value = false
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'stockTransferOrderDetail-com.slip.spd.entity.vo.stock.TransferOrderDetailVO',
    orderIds: [infoList.data.id],
  }
  getTransferOrderPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('transferOrder:price')
      )
    }
  })
}
//提交
function submit() {
  const ids = [infoList.data.id]
  submitTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
// 审核
function check() {
  const ids = [infoList.data.id]
  checkTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
// 驳回
function reject() {
  const ids = [infoList.data.id]
  rejectTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
//移库
function transfer() {
  let ids = [infoList.data.id]
  transferTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
function doCancel() {
  transfersCancel(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      returnModify()
    }
  })
}
//取消上架
function cancelPutTransfer() {
  proxy
    .$confirm('确认取消上架吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let id = infoList.data.id
      transferCancelPut(id).then((resp) => {
        if (resp && resp.success) {
          returnModify()
        }
      })
    })
    .catch(() => {})
}
//取消上架
function cancelDownTransfer() {
  proxy
    .$confirm('确认取消拣货吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let id = infoList.data.id
      transfersCancelDownShelf(id).then((resp) => {
        if (resp && resp.success) {
          returnModify()
        }
      })
    })
    .catch(() => {})
}
//移库并消耗
function tally() {
  let ids = [infoList.data.id]
  tallyTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
function revoke() {
  //撤销
  let ids = [infoList.data.id]
  revokeTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
function revokable() {
  //撤回
  //校验库存产品是否充足
  validateRevoke(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      revokeInfo.visible = true
      revokeInfo.id = infoList.data.id
    }
  })
}
//导出excel
function exportExcel() {
  exportExcelTransferOrder(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'stockTransferOrderDetail-com.slip.spd.entity.vo.stock.TransferOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      tableInfo.summaryFieldList.forEach((item) => {
        item.label = data.detail[item.value].label
      })
      getMain()
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden > .el-table) {
  overflow-y: hidden;
}
</style>
